package com.weasel.weixin.commons;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableMap;
import com.weasel.http.HttpClientSecretary;
import com.weasel.weixin.commons.config.CommonConfig;
import com.weasel.weixin.commons.config.CommonConsts;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Created by Dylan on 2015/9/28.
 */
public class AccessTokenRequest extends CommonRequest{

    private final static int availableAccessTokenTime = 7200 - 5;

    private final static Cache<String,String> ACCESS_TOKEN_CACHE = CacheBuilder.newBuilder().expireAfterWrite(availableAccessTokenTime, TimeUnit.SECONDS).maximumSize(1).build();

    public AccessTokenRequest(CommonConfig config) {
        super(config);
    }


    public String getAccessToken() throws ExecutionException {

        return ACCESS_TOKEN_CACHE.get("accessToken", new Callable<String>() {
            @Override
            public String call() throws Exception {
                return refreshAccessToken();
            }
        });
    }

    public  String refreshAccessToken() throws IOException {

        Map<String,String> params = ImmutableMap.of("grant_type", "client_credential", "appid", config.getAppid(), "secret", config.getSecret());

        AccessTokenResponse response = HttpClientSecretary.get()
                                                          .withURI(CommonConsts.ACCESS_TOKEN_URL)
                                                          .withParams(params)
                                                          .doItWithJson(AccessTokenResponse.class);
        if(response.isOK()){
            ACCESS_TOKEN_CACHE.put("accessToken",response.getAccessToken());
        }
        return response.getAccessToken();
    }

}
